#! /usr/bin/env python
# -*- coding: utf-8 -*-

import os
import time

import FileHostProtoType

class nlitem(FileHostProtoType.HostItem):
    def __init__(self, name, type, id, link, encrypt_name='', server_name=''): 
        #id save as D111111 or F1111111 
        FileHostProtoType.HostItem.__init__(self, name, type, id, link, encrypt_name, server_name)

class netloadin(FileHostProtoType.FileHostProcess):
    def __init__(self,user,pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "Netload.in"
        self.domain = '.netload.in'
        self.logtype = 'poster'
        self._opener = None
        self._cj = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
        self.auth_code = ''
        self._cookieCurl = self._user + '_netloadin.cookie'
        self._cookieCurl = os.path.join(os.path.dirname(__file__), self._cookieCurl)
            
    def login(self):
        '''
        login to FileSonic
        return opener object which includes cookies
        '''
        self.generateOpener()
        #try to restore cookiejar
        if self.restore_cookiejar():
            return True
        
        self.fherr.write('login to Netload.in %s/%s...' % (self._user,'*'*len(self._pwd)))
        loginData = {'txtuser' : self._user, \
                     'txtpass' : self._pwd, \
                     'txtcheck' : 'login',
                     'txtlogin' : '&#30331;&#24405;'}
        response = self.loginFileHost("http://netload.in/index.php", loginData)
        cookie_status = self.check_cookie()
        if not cookie_status:
            self.fherr.write("[%s]User %s Status : not Logined." % (time.ctime(), self._user))
            self.fherr.write(response)
            return False
        self.fherr.write('write cookie file.')
        try:
            os.remove(self._cookieCurl)
        except:
            self.fherr.write('Exception occured when deling Local Cookie.')
        self._cj.save(self._cookieCurl, ignore_discard=True)
        return True   
        
    def restore_cookiejar(self):
        '''
        load cookie file, then access website to verify if cookie is avaiable
        '''
        if os.path.isfile(self._cookieCurl):
            self.fherr.write('Restore Local Cookie.')
            try:
                self._cj.load(self._cookieCurl, ignore_discard=True)
            except:
                self.fherr.write('Failed to Restore Local CookieJar.')
            #access website to conferm cookie is avaiable
            return self.check_cookie()
        return False
    
    def check_cookie(self):
        self.fherr.write('Checking Cookie...')
        response = self.post_request('http://netload.in/index.php?id=2')
        if response and self._user in response:
            self.fherr.write("User %s Status : Logined." % self._user)
            self.islogin = True             
            return True
        self.fherr.write("[%s]User %s Status : not Logined." % (time.ctime(), self._user))
        self.fherr.write(response)
        return False
    
    def getFileList(self):
        return []
    
    def getFilesFromFolder(self, folder):
        id  = folder.id
        return []
    
    def getFolderList(self):   
        foundFolders = []
        foundFolders.sort()
        return foundFolders 

    def createFolder(self, newfolder):
        foundfolder = self.findFolder(newfolder)
        if foundfolder is None:
            #netloadin no longer allow user to create subdir 
            return self.__newFolder(newfolder)
        self.fherr.write("Folder %s exsits." % newfolder)
        return foundfolder

    def __newFolder(self, newfolder, parentfolder=None):
        return None
    
    def moveto(self, items, destFolder):
        pass
            
    def upload_web(self, file, progressLog=None, other_args=None, send_range=None):
        return self.upload_web_local(file, progressLog, other_args, send_range)    
    
    def upload_to_ftp(self, file, progressLog=None, other_args=None):
        self.fherr.write("ftp mode is not impl.")
        return None
    
    def upload_web_local(self, file, progressLog=None, other_args=None, send_range=None):
        if not self.auth_code:
            auth_api = "http://www.netload.in/index.php?id=56&get=Get%20Auth%20Code"        
            auth = self.post_request(auth_api)        
            auth_code = self.get_upload_key(auth, "Your Auth Code:", -1, '"')        
            auth_code = auth_code[1:-8]
            self.auth_code = auth_code
        
        server_api = 'http://api.netload.in/getserver.php'
        upload_link = self.post_request(server_api)
        print upload_link
        
        filesize = os.path.getsize(file)
        filename = self.rename_func(file)
        start_point = 0
        info = "Uploading...%s" % file
        if send_range is not None:
            #range is a 3-tuple, <start, end, number>
            filesize = send_range[1] - send_range[0] + 1
            filename += ".%03d" % send_range[2]
            start_point = send_range[0]
            info += " part%d" % send_range[2]
        
        fileobj = open(file, 'rb')
        fileobj.seek(start_point) 
        
        data = {}
        data['file_link'] = fileobj
        data['auth'] = self.auth_code
        data['modus'] = 'file_upload'
        data['user_id'] = self._user
        data['user_password'] = self._pwd
        
        if other_args:
            rar_password = other_args.get('rar_password')
            data['archive_password'] = rar_password
        
        
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        
        self.fherr.write(info)
        
        resultMsg = self.post_request(upload_link, \
                                   data, \
                                   cb=callback, \
                                   retry=1, \
                                   setfilename=filename, \
                                   setfilesize=filesize)
                    
        if resultMsg is None:
            self.fherr.write("UploadTask(%s) was Stop by user." % file)
            return
        
        print resultMsg
        if 'rar_password' in resultMsg:
            self.fherr.write('We should tell the server pass')
        if 'UPLOAD_OK' in resultMsg:
            tokens = resultMsg.split(';')
            basename = os.path.basename(file)
            server_file_size = int(tokens[2])
            if not server_file_size == filesize:
                self.fherr.write('Wrong filesize!')
            download_link = tokens[3]
            item = nlitem(basename, 'file', '', download_link, filename)
            self.newupload.append(item)
            return item
        else:
            self.fherr.write('Upload Failed. Here is the server response.')
            self.fherr.write(resultMsg)